using System;
using System.Collections.Generic;
using Castle.ActiveRecord.Framework;
using NHibernate;
using NHibernate.Expression;
using Castle.ActiveRecord;

namespace CosyTrade.Data
{
    internal class DataAccessBase 
    {
        public static void Initialize(IConfigurationSource source, params Type[] ormTypes)
        {
            ActiveRecordStarter.Initialize(source, ormTypes);
        }

        public static void Create(BusinessObject instance)
        {
            ActiveRecordMediator.Create(instance);
        }

        public static void Save(BusinessObject instance)
        {
            ActiveRecordMediator.Save(instance);
        }

        public static void Delete(BusinessObject instance)
        {
            instance.IsDeleteRecord = true;
            ActiveRecordMediator.Save(instance);
        }

        public static T FindByPrimaryKey<T>(Guid primaryKey) 
        {
            return (T) FindByPrimaryKey(typeof (T), primaryKey);
        }

        public static object FindByPrimaryKey(Type type, Guid primaryKey)
        {
            return ActiveRecordMediator.FindByPrimaryKey(type, primaryKey);
        }

        public static T FindOne<T>(params ICriterion[] criterion)
        {
            return (T) ActiveRecordMediator.FindOne(typeof(T), criterion);
        }

        public static T FindOne<T>(DetachedCriteria criterion) where T : class
        {
            return ActiveRecordMediator<T>.FindOne(criterion);
        }

        public static IList<T> FindAll<T>(params ICriterion[] criterias)
        {
            return (IList<T>) ActiveRecordMediator.FindAll(typeof (T), criterias);
        }

        public static IList<T> FindAll<T>(Order[] orderBy, params ICriterion[] criterias)
        {
            return (IList<T>) ActiveRecordMediator.FindAll(typeof(T), orderBy, criterias);
        }

        public static IList<T> SlicedFindAll<T>(int firstResult, int maxResult, params ICriterion[] criterias)
        {
            return (IList<T>) ActiveRecordMediator.SlicedFindAll(typeof (T), firstResult, maxResult, criterias);
        }

        public static IList<T> SlicedFindAll<T>(int firstResult, int maxResult, Order[] orderBy, params ICriterion[] criterias)
        {
            return (IList<T>) ActiveRecordMediator.SlicedFindAll(typeof (T), firstResult, maxResult, orderBy, criterias);
        }

        public static object UniqueResult(Type type, DetachedCriteria detachedCriteria)
        {
            ISession session = ActiveRecordMediator.GetSessionFactoryHolder().CreateSession(type);
            ICriteria criteria = detachedCriteria.GetExecutableCriteria(session);
            object reValue = criteria.UniqueResult();
            ActiveRecordMediator.GetSessionFactoryHolder().ReleaseSession(session);
            return reValue;
        }
    }
}